<template>
    <view class="upload-container">
        <view type="primary" v-if="fileList.length == 0" class="choose-btn" @click="chooseFiles">选择文件</view>
        <view class="file-list">
            <view v-for="(file, index) in fileList" :key="index" class="file-item">
                <text class="file-link" @click="previewFile(file)">{{ file.name }}</text>
                <text class="delete-btn" @click="deleteFile(index)">删除</text>
            </view>
        </view>
        <view v-if="uploading" class="custom-loading-mask">
            <uv-loading-icon text="加载中..." />
        </view>
    </view>
</template>
<script>
import { BASEURL } from '@/utils/request.js'
export default {
    props: {
        maxCount: {
            type: Number,
            default: 1
        },
        maxFileSize: {
            type: Number,
            default: 1024 * 1024 * 20 //文件大小
        },
        allowedExtensions: {
            type: Array,
            default: () => []// 允许的文件类型
        },
        formData: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            fileList: [],
            uploading: false,
            filePath: ''
        }
    },
    onLoad() {
    },
    methods: {
        deleteFile(index) {
            this.fileList.splice(index, 1);
        },

        chooseFiles() {
            const token = uni.getStorageSync("token");
            // #ifdef APP-PLUS
            console.log(151);
            const MediaStore = plus.android.importClass('android.provider.MediaStore');
            const main = plus.android.runtimeMainActivity();
            const Uri = plus.android.importClass('android.net.Uri');
            plus.io.chooseFile({
                title: '选择文件',
                filetypes: this.allowedExtensions, // 允许的文件类型
                multiple: false, // 是否允许多选
            },
                (res) => {

                    // const tempFilePaths = e.files
                    // 获取文件的虚拟路径
                    const contentUri = decodeURIComponent(res.files[0])
                    const uri = MediaStore.Files.getContentUri("external");
                    // 给系统导入 contentResolver
                    plus.android.importClass(main.getContentResolver());
                    const arr = contentUri.split(':')
                    // 通过查询的方式用虚拟路径的id1获取到文件的真实路径
                    let cursor = main.getContentResolver().query(uri, ['_data'], "_id=?", [arr[arr.length - 1]], null);
                    plus.android.importClass(cursor);
                    let result
                    if (cursor != null && cursor.moveToFirst()) {
                        let column_index = cursor.getColumnIndexOrThrow('_data');
                        result = cursor.getString(column_index)   // result即文件的真实路径
                        cursor.close();
                    }
                    result = 'file://' + result
                    // this.uploading = true;
                    uni.showLoading({ title: '上传中...' });
                    this.filePath = result // 此路径为文件的本地真实路径，可使用该路径进行上传文件
                    uni.uploadFile({
                        url: `${BASEURL}/common/upload`,
                        filePath: this.filePath,
                        name: 'file',
                        header: {
                            'Authorization': token
                        },
                        success: (uploadFileRes) => {
                            let data;
                            try {
                                data = JSON.parse(uploadFileRes.data);
                            } catch (e) {
                                uni.showToast({ title: '上传失败', icon: 'none' });
                                return;
                            }
                            if (data && data.annexUrl) {
                                //从data中获取annexName后缀名
                                const isType = data.annexName.split('.').pop();
                                this.fileList.push({
                                    name: data.annexName,
                                    url: data.annexUrl,
                                    isType: isType

                                });
                                this.$emit('success', {
                                    name: data.annexName,
                                    url: data.annexUrl,
                                    isType: isType
                                });
                            }
                        },
                        complete: () => {
                            // this.uploading = false;
                            uni.hideLoading();
                        },
                        fail: (err) => {
                            console.error('上传失败:', err);
                        }
                    });


                },
                (err) => {
                    console.error('选择文件失败:', err);
                }
            );
            // #endif

            // #ifdef H5
            // H5环境下的文件选择
            uni.chooseFile({
                count: this.maxCount,
                type: 'all',
                success: (res) => {
                    console.log(res, 56);

                    const validFiles = res.tempFiles.filter(file => {
                        const ext = this.getFileExtension(file.name).toLowerCase();
                        return this.allowedExtensions.includes(ext);
                    });
                    // 过滤大小
                    const oversizedFiles = validFiles.filter(file => file.size > this.maxFileSize);
                    if (oversizedFiles.length > 0) {
                        uni.showToast({
                            title: `文件不能超过${this.maxFileSize / (1024 * 1024)}MB`,
                            icon: 'none'
                        });
                    }
                    const finalFiles = validFiles.filter(file => file.size <= this.maxFileSize);

                    if (finalFiles.length === 0) {
                        return;
                    }
                    this.uploading = true;
                    uni.showLoading({ title: '上传中...' });
                    if (validFiles.length === 0) {
                        uni.showToast({
                            title: '请选择指定类型文件',
                            icon: 'none'
                        });
                        return;
                    }
                    validFiles.forEach(file => {
                        const ext = this.getFileExtension(file.name).toLowerCase();
                        file.isImage = this.allowedExtensions.includes(ext);
                        file.isPdf = ext === 'pdf';
                        uni.uploadFile({
                            url: `${BASEURL}/common/upload`,
                            filePath: file.path,
                            name: 'file',
                            formData: this.formData,
                            header: {
                                'Authorization': token
                            },
                            success: (uploadFileRes) => {
                                let data;
                                try {
                                    data = JSON.parse(uploadFileRes.data);
                                } catch (e) {
                                    uni.showToast({ title: '上传失败', icon: 'none' });
                                    return;
                                }
                                if (data && data.annexUrl) {
                                    //从data中获取annexName后缀名
                                    const isType = data.annexName.split('.').pop();
                                    this.fileList.push({
                                        name: file.name,
                                        url: data.annexUrl,
                                        isType: isType

                                    });
                                    this.$emit('success', {
                                        name: data.annexName,
                                        url: data.annexUrl,
                                        isType: isType
                                    });
                                }
                            },
                            complete: () => {
                                this.uploading = false;
                                uni.hideLoading();
                            }
                        });
                    });

                    uni.showToast({
                        title: `已选择 ${validFiles.length} 个文件`,
                        icon: 'none'
                    });
                },
                fail: (err) => {
                    console.error('选择文件失败:', err);
                }
            });
            // #endif
        },
        getFileExtension(filename) {
            return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
        },
        previewFile(file) {
            uni.showLoading({ title: '加载中...' });
            if (file.isType == 'jpg' || file.isType == 'jpeg') {
                uni.previewImage({
                    urls: [file.url],
                    success: () => {
                        uni.hideLoading();
                    },
                    fail: () => {
                        uni.hideLoading();
                    }
                });
            } else if (file.isType == 'pdf') {
                uni.downloadFile({
                    url: file.url,
                    success: function (res) {
                        var filePath = res.tempFilePath;
                        uni.openDocument({
                            filePath: filePath,
                            // showMenu 是 uni.openDocument 的参数，用于控制是否显示右上角菜单（如分享、收藏等），true 表示显示菜单
                            showMenu: true,
                            success: function (res) {
                                console.log('打开文档成功');
                                uni.hideLoading();
                            },
                            fail: function (err) {
                                console.log('打开文档失败:', err);
                                uni.hideLoading();
                            }
                        });
                    },
                    fail: function (err) {
                        console.log('下载失败:', err);
                        uni.hideLoading();
                    }
                });
            } else {
                // 其他类型可下载或用 webview 预览
                uni.downloadFile({
                    url: file.url,
                    success: (res) => {
                        console.log(res, 228);
                        const filePath = res.tempFilePath;
                        uni.openDocument({
                            filePath: filePath,
                            showMenu: true,
                            success: (res) => {
                                console.log('打开成功');
                                uni.hideLoading();
                            },
                            fail: (err) => {
                                console.log('打开失败:', err);
                                uni.hideLoading();
                            }
                        });
                    },
                    fail: (err) => {
                        console.log('下载失败:', err);
                        uni.hideLoading();
                    }
                });
            }
        }
    },


}
</script>
<style lang="scss" scoped>
.preview-list {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin-top: 20px;
}

.upload-container {
    display: flex;
}

// .file-list {
//     margin-top: 20rpx;
// }

.file-item {
    margin-bottom: 10rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.file-link {
    max-width: 400rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #2878ff;
    text-decoration: underline;
    cursor: pointer;
}

.document-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background: #f0f0f0;
}

.delete-btn {
    color: #f53f3f;
    margin-left: 20rpx;
    cursor: pointer;
    font-size: 28rpx;
}
</style>